/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */
package com.excesys.exsecs.om.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.excesys.exsecs.common.core.util.R;
import com.excesys.exsecs.common.excel.vo.ErrorMessage;
import com.excesys.exsecs.om.entity.OmInspectionAreaClassification;
import com.excesys.exsecs.om.mapper.OmInspectionAreaClassificationMapper;
import com.excesys.exsecs.om.service.OmInspectionAreaClassificationService;
import com.excesys.exsecs.om.vo.RegionalClassificationExcelVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @date 2023-05-19
 */
@RequiredArgsConstructor
@Service
public class OmInspectionAreaClassificationServiceImpl
		extends ServiceImpl<OmInspectionAreaClassificationMapper, OmInspectionAreaClassification>
		implements OmInspectionAreaClassificationService {

	private final OmInspectionAreaClassificationMapper omInspectionAreaClassificationMapper;

	@Override
	public List<Tree<String>> getList(List<OmInspectionAreaClassification> list) {
		System.out.println("输出list：" + list);
		List<Tree<String>> lists = TreeUtil.build(list, "0", (node, tree) -> {
			tree.setId(node.getId().toString());
			tree.setName(node.getName());
			tree.setParentId(node.getParentId().toString());
			// 额外的值
			tree.put("moduleNo", node.getModuleNo());
		});
		System.out.println("转换后树状数据：" + JSON.toJSONString(lists));
		return lists;
	}

	@Override
	public List<Tree<String>> getInspectionList(List<OmInspectionAreaClassification> list) {
		System.out.println("输出list：" + list);
		List<Tree<String>> lists = TreeUtil.build(list, "0", (node, tree) -> {
			tree.setId(node.getId().toString());
			tree.setName(node.getName());
			tree.setParentId(node.getParentId().toString());
			// 额外的值
			tree.put("moduleNo", node.getModuleNo());
			tree.put("value", node.getId().toString());
			tree.put("label", node.getName());
		});
		System.out.println("转换后树状数据：" + JSON.toJSONString(lists));
		return lists;
	}

	@Override
	public List<OmInspectionAreaClassification> getParentList() {
		List<OmInspectionAreaClassification> list = omInspectionAreaClassificationMapper.getParentList();
		return list;
	}

	@Override
	public List<OmInspectionAreaClassification> getChildList(String parentId) {
		List<OmInspectionAreaClassification> list = new ArrayList<>();
		try {
			list = omInspectionAreaClassificationMapper.getChildList(parentId);
		}
		catch (Exception e) {
			return null;
		}

		return list;
	}

	@Override
	public List<OmInspectionAreaClassification> getInspectionAreaList(String name) {
		List<OmInspectionAreaClassification> list = omInspectionAreaClassificationMapper.getInspectionAreaList(name);
		return list;
	}

	@Override
	public OmInspectionAreaClassification getByid(String id) {
		OmInspectionAreaClassification omInspectionAreaClassification = omInspectionAreaClassificationMapper
				.getByid(id);
		return omInspectionAreaClassification;
	}

	@Override
	public OmInspectionAreaClassification getName(String id) {
		OmInspectionAreaClassification omInspectionAreaClassification = omInspectionAreaClassificationMapper
				.getName(id);
		return omInspectionAreaClassification;
	}

	@Override
	public List<OmInspectionAreaClassification> getList() {
		List<OmInspectionAreaClassification> list = omInspectionAreaClassificationMapper.getList();
		return list;
	}

	@Override
	public List<RegionalClassificationExcelVo> listBamSBuildings() {
		List<OmInspectionAreaClassification> bamSBuildings = this.list(Wrappers.emptyWrapper());
		// 转换成execl 对象输出
		return bamSBuildings.stream().map(buildings -> {
			RegionalClassificationExcelVo regionalClassificationExcelVo = new RegionalClassificationExcelVo();
			BeanUtil.copyProperties(buildings, regionalClassificationExcelVo);
			return regionalClassificationExcelVo;
		}).collect(Collectors.toList());
	}

	@Override
	public R importBamSBuildings(List<RegionalClassificationExcelVo> excelVOList, BindingResult bindingResult) {
		// 通用校验获取失败的数据
		List<ErrorMessage> errorMessageList = (List<ErrorMessage>) bindingResult.getTarget();
		int sucess = 0;
		int fail = 0;

		// 执行数据插入操作 组装 RoleDto
		for (RegionalClassificationExcelVo excel : excelVOList) {
			// 个性化校验逻辑
			List<OmInspectionAreaClassification> postList = this.list();
			// 检验区域或者NFC编码是否存在
			Set<String> errorMsg = new HashSet<>();
			boolean existPost = postList.stream().anyMatch(post -> excel.getName().equals(post.getName()));
			if (existPost) {
				errorMsg.add("区域分类存在重复" + excel.getName());
			}

			// 数据合法情况
			if (CollUtil.isEmpty(errorMsg)) {
				int num = insertBamSBuildings(excel);
				if (num == 1) {
					fail++;
				}
				else {
					sucess++;
				}
			}
			else {
				// 数据不合法情况
				errorMessageList.add(new ErrorMessage(excel.getLineNum(), errorMsg));
			}
		}
		if (CollUtil.isNotEmpty(errorMessageList)) {
			return R.failed(errorMessageList);
		}
		return R.ok(sucess, "成功导入数量" + sucess + "。" + "存在" + fail + "重复");
	}

	@Override
	public OmInspectionAreaClassification getByName(String name) {
		OmInspectionAreaClassification omInspectionAreaClassification = omInspectionAreaClassificationMapper
				.getByName(name);
		return omInspectionAreaClassification;
	}

	@Override
	public Page setPage(List<OmInspectionAreaClassification> omInspectionAreaClassification, Page page) {
		if (omInspectionAreaClassification == null) {
			return null;
		}
		int size = omInspectionAreaClassification.size();
		int pageSize = (int) page.getSize();
		if (pageSize > size) {
			pageSize = size;
		}
		int pageCurrent = (int) page.getCurrent();
		if (pageSize != 0) {
			// 求出最大页数，防止currentPage越界
			int maxPage = size % pageSize == 0 ? size / pageSize : size / pageSize + 1;

			if (pageCurrent > maxPage) {
				pageCurrent = maxPage;
			}
		}
		// 当前页第一条数据的下标
		int curIdx = pageCurrent > 1 ? (pageCurrent - 1) * pageSize : 0;

		List pageList = new ArrayList();

		// 将当前页的数据放进pageList
		for (int i = 0; i < pageSize && curIdx + i < size; i++) {
			pageList.add(omInspectionAreaClassification.get(curIdx + i));
		}

		page.setCurrent(pageCurrent).setSize(pageSize).setTotal(omInspectionAreaClassification.size())
				.setRecords(pageList);
		return page;
	}

	private int insertBamSBuildings(RegionalClassificationExcelVo excel) {
		OmInspectionAreaClassification classification = new OmInspectionAreaClassification();
		classification.setName(excel.getName());
		classification.setParentId(0L);
		this.save(classification);
		return 0;
	}

}
